package com.example.bookshelf.ui.screen

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.example.bookshelf.BookShelfApplication
import com.example.bookshelf.data.BookShelfRepository
import com.example.bookshelf.network.Book
import kotlinx.coroutines.launch
import retrofit2.HttpException
import java.io.IOException

class BookShelfViewModel(private val bookShelfRepository: BookShelfRepository) : ViewModel() {
    var state by mutableStateOf<BookShelfState>(BookShelfState.Loading)
        private set

    init {
        getBooks(bookType = "jazz+history")
    }

    fun getBooks(bookType: String) {
        state = BookShelfState.Loading
        viewModelScope.launch {
            state = try {
                BookShelfState.Success(bookShelfRepository.getBooks(bookType))
            } catch (e: IOException) {
                BookShelfState.Error
            } catch (e: HttpException) {
                BookShelfState.Error
            }
        }
    }

    companion object {
        val Factory: ViewModelProvider.Factory = viewModelFactory {
            initializer {
                BookShelfViewModel(
                    bookShelfRepository = (this[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY] as BookShelfApplication).container.bookShelfRepository
                )
            }
        }
    }
}

sealed interface BookShelfState {
    data class Success(val books: List<Book>) : BookShelfState
    data object Loading : BookShelfState
    data object Error : BookShelfState
}